<?php
namespace app\api\service;

use think\Exception;
use think\Cache;
use think\Request;

class Token {

    // 生成令牌
    public static function generateToken()
    {
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('config.token_salt');
        return md5($randChar . $timestamp . $tokenSalt);
    }

    // 保存token 到缓存
    public static function saveToken($res) {
        $key = self::generateToken();
        $value = json_encode($res);

        $result = cache($key, $value, 3600);
        
        if (!$result) {
            return show(0, '服务器异常', [], 400);
        }

        return $key;
    }

    /**
     * 调用授予token 
     * 参数 用户信息 
     * 参数 access
     * return token
     */
    public static function grantToken($result, $access) {
        $cacheValue['user'] = $result;
        $cacheValue['access'] = $access;
        $token = self::saveToken($cacheValue);
        return $token;
    }

    // // 判断权限
    // public static function checkCurrent($access){

    //     self::getCache('access');
    // }

    // 是否有
    public static function verifyToken($token)
    {
        $exist = Cache::get($token);
        if($exist){
            return true;
        }
        else{
            return false;
        }
    }

    public function getToken($code='')
    {
        $token = self::grantToken($code, 'xxx');
        return [
            'token' => $token
        ];
    }


    
}